package com.khh.servlet;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by webrx on 2017-09-06.
 */
@WebServlet("/download")
public class Download extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //String fileName = "aa.rar";
        //动态获取要下载文件名
        String fileName = req.getParameter("name");
        String downname = new SimpleDateFormat("yyyyMMddhhmmssS").format(new Date())+fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        String path = req.getServletContext().getRealPath("/upload/");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("multipart/form-data");
        resp.setHeader("Content-Disposition", "attachment;fileName=" + downname);
        //读取文件
        InputStream is = new FileInputStream(path+"/"+fileName);
        //下载文件
        OutputStream os = resp.getOutputStream();
        //文件缓存10k
        byte[] buf = new byte[10240];
        int i = 0;
        while((i = is.read(buf)) > 0)    {
            os.write(buf, 0, i);
        }
        os.flush();
        os.close();
        is.close();
    }
}
